package com.example.shortvideobackend.config;

import com.example.shortvideobackend.entity.User;
import com.example.shortvideobackend.entity.Video;
import com.example.shortvideobackend.entity.Comment;
import com.example.shortvideobackend.entity.Like;
import com.example.shortvideobackend.entity.Follow;
import com.example.shortvideobackend.entity.LiveStream;
import com.example.shortvideobackend.repository.UserRepository;
import com.example.shortvideobackend.repository.VideoRepository;
import com.example.shortvideobackend.repository.CommentRepository;
import com.example.shortvideobackend.repository.LikeRepository;
import com.example.shortvideobackend.repository.FollowRepository;
import com.example.shortvideobackend.repository.LiveStreamRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

@Component
public class DataInitializer implements CommandLineRunner {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private VideoRepository videoRepository;

    @Autowired
    private CommentRepository commentRepository;

    @Autowired
    private LikeRepository likeRepository;

    @Autowired
    private FollowRepository followRepository;

    @Autowired
    private LiveStreamRepository liveStreamRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public void run(String... args) throws Exception {
        // 检查是否已有数据
        if (userRepository.count() == 0) {
            initializeUsers();
        }
        
        // 重新获取用户数据，确保数据已保存
        List<User> users = userRepository.findAll();
        if (videoRepository.count() == 0 && users.size() >= 1) {
            initializeVideos(users);
        } else if (videoRepository.count() == 0) {
            System.out.println("用户数据不足，无法初始化视频数据。用户数量: " + users.size());
        }

        // 初始化其他表的数据
        List<Video> videos = videoRepository.findAll();
        if (commentRepository.count() == 0 && !videos.isEmpty()) {
            initializeComments(users, videos);
        }
        
        if (likeRepository.count() == 0 && !videos.isEmpty()) {
            initializeLikes(users, videos);
        }
        
        if (followRepository.count() == 0 && users.size() >= 2) {
            initializeFollows(users);
        }
        
        if (liveStreamRepository.count() == 0 && users.size() >= 1) {
            initializeLiveStreams(users);
        }
    }

    private void initializeUsers() {
        List<User> users = Arrays.asList(
            createUser("一次就好718", "user1@example.com", "123456", "创业达人，分享有趣故事"),
            createUser("霾癆影视", "user2@example.com", "123456", "专业影视制作，记录精彩瞬间"),
            createUser("猫咪爱好者", "user3@example.com", "123456", "爱猫人士，分享猫咪日常"),
            createUser("唢呐吴振", "user4@example.com", "123456", "传统技艺传承人"),
            createUser("美食达人", "user5@example.com", "123456", "美食制作教程分享"),
            createUser("旅行者小王", "user6@example.com", "123456", "旅行vlog博主")
        );

        userRepository.saveAll(users);
        System.out.println("虚拟用户数据初始化完成，共创建 " + users.size() + " 个用户");
    }

    private User createUser(String username, String email, String password, String bio) {
        User user = new User();
        user.setUsername(username);
        user.setEmail(email);
        user.setPassword(passwordEncoder.encode(password));
        user.setBio(bio);
        user.setAvatar("https://picsum.photos/100/100?random=" + username.hashCode());
        user.setCreatedAt(LocalDateTime.now());
        return user;
    }

    private void initializeVideos(List<User> users) {
        // 确保有足够的用户，如果不够则重复使用第一个用户
        User defaultUser = users.get(0);
        
        List<Video> videos = Arrays.asList(
            createVideo("带三位女室友开公司", "创业路上的有趣故事", 
                "https://sample-videos.com/zip/10/mp4/SampleVideo_1280x720_1mb.mp4",
                "https://picsum.photos/300/400?random=1",
                users.size() > 0 ? users.get(0) : defaultUser, 12580, 231),
            
            createVideo("军事训练日常", "军人的日常生活", 
                "https://sample-videos.com/zip/10/mp4/SampleVideo_1280x720_2mb.mp4",
                "https://picsum.photos/300/400?random=2",
                users.size() > 1 ? users.get(1) : defaultUser, 8920, 4666),
            
            createVideo("被一只猫整无语了", "可爱猫咪的日常", 
                "https://sample-videos.com/zip/10/mp4/SampleVideo_1280x720_5mb.mp4",
                "https://picsum.photos/300/400?random=3",
                users.size() > 2 ? users.get(2) : defaultUser, 15670, 506),
            
            createVideo("今天又喜收万家岭爱徒一名", "传统技艺传承", 
                "https://sample-videos.com/zip/10/mp4/SampleVideo_1280x720_10mb.mp4",
                "https://picsum.photos/300/400?random=4",
                users.size() > 3 ? users.get(3) : defaultUser, 7230, 239),
            
            createVideo("美食制作教程", "简单易学的家常菜", 
                "https://sample-videos.com/zip/10/mp4/SampleVideo_1280x720_1mb.mp4",
                "https://picsum.photos/300/400?random=5",
                users.size() > 4 ? users.get(4) : defaultUser, 18920, 892),
            
            createVideo("旅行vlog - 云南之旅", "美丽的云南风景", 
                "https://sample-videos.com/zip/10/mp4/SampleVideo_1280x720_2mb.mp4",
                "https://picsum.photos/300/400?random=6",
                users.size() > 5 ? users.get(5) : defaultUser, 11250, 567),
            
            createVideo("王者荣耀排位赛", "精彩游戏对局", 
                "https://sample-videos.com/zip/10/mp4/SampleVideo_1280x720_1mb.mp4",
                "https://picsum.photos/300/400?random=7",
                defaultUser, 23450, 1234),
            
            createVideo("和平精英吃鸡挑战", "刺激的生存游戏", 
                "https://sample-videos.com/zip/10/mp4/SampleVideo_1280x720_2mb.mp4",
                "https://picsum.photos/300/400?random=8",
                defaultUser, 18760, 892),
            
            createVideo("舞蹈教学 - 街舞基础", "零基础学街舞", 
                "https://sample-videos.com/zip/10/mp4/SampleVideo_1280x720_5mb.mp4",
                "https://picsum.photos/300/400?random=9",
                defaultUser, 9870, 456),
            
            createVideo("音乐创作 - 原创歌曲", "我的音乐作品", 
                "https://sample-videos.com/zip/10/mp4/SampleVideo_1280x720_10mb.mp4",
                "https://picsum.photos/300/400?random=10",
                defaultUser, 6540, 234),
            
            createVideo("手工制作 - 陶艺教程", "传统手工艺", 
                "https://sample-videos.com/zip/10/mp4/SampleVideo_1280x720_1mb.mp4",
                "https://picsum.photos/300/400?random=11",
                defaultUser, 5430, 178),
            
            createVideo("健身教程 - 居家锻炼", "在家也能健身", 
                "https://sample-videos.com/zip/10/mp4/SampleVideo_1280x720_2mb.mp4",
                "https://picsum.photos/300/400?random=12",
                defaultUser, 8760, 345)
        );

        videoRepository.saveAll(videos);
        System.out.println("虚拟视频数据初始化完成，共创建 " + videos.size() + " 个视频");
    }

    private Video createVideo(String title, String description, String videoUrl, String thumbnail, 
                            User user, Integer views, Integer likes) {
        Video video = new Video();
        video.setTitle(title);
        video.setDescription(description);
        video.setVideoUrl(videoUrl);
        video.setThumbnail(thumbnail);
        video.setUser(user);
        video.setViews(views);
        video.setLikes(likes);
        video.setCreatedAt(LocalDateTime.now().minusDays((long) (Math.random() * 30)));
        return video;
    }

    private void initializeComments(List<User> users, List<Video> videos) {
        Random random = new Random();
        List<Comment> comments = Arrays.asList(
            createComment("这个视频太有趣了！", users.get(0), videos.get(0)),
            createComment("军人的生活真是丰富多彩！", users.get(0), videos.get(1)),
            createComment("猫咪真的太可爱了！", users.get(0), videos.get(2)),
            createComment("传统技艺真是博大精深！", users.get(0), videos.get(3)),
            createComment("美食教程看着就想吃！", users.get(0), videos.get(4)),
            createComment("旅行vlog好想去云南！", users.get(0), videos.get(5)),
            createComment("游戏对局太精彩了！", users.get(0), videos.get(6)),
            createComment("生存游戏太刺激了！", users.get(0), videos.get(7)),
            createComment("街舞教学很实用！", users.get(0), videos.get(8)),
            createComment("音乐作品很有才华！", users.get(0), videos.get(9)),
            createComment("手工制作很有意思！", users.get(0), videos.get(10)),
            createComment("健身教程很专业！", users.get(0), videos.get(11))
        );
        commentRepository.saveAll(comments);
        System.out.println("虚拟评论数据初始化完成，共创建 " + comments.size() + " 条评论");
    }

    private Comment createComment(String content, User user, Video video) {
        Comment comment = new Comment();
        comment.setContent(content);
        comment.setUser(user);
        comment.setVideo(video);
        comment.setCreatedAt(LocalDateTime.now().minusDays((long) (Math.random() * 30)));
        return comment;
    }

    private void initializeLikes(List<User> users, List<Video> videos) {
        Random random = new Random();
        List<Like> likes = Arrays.asList(
            createLike(users.get(0), videos.get(0)),
            createLike(users.get(0), videos.get(1)),
            createLike(users.get(0), videos.get(2)),
            createLike(users.get(0), videos.get(3)),
            createLike(users.get(0), videos.get(4)),
            createLike(users.get(0), videos.get(5)),
            createLike(users.get(0), videos.get(6)),
            createLike(users.get(0), videos.get(7)),
            createLike(users.get(0), videos.get(8)),
            createLike(users.get(0), videos.get(9)),
            createLike(users.get(0), videos.get(10)),
            createLike(users.get(0), videos.get(11))
        );
        likeRepository.saveAll(likes);
        System.out.println("虚拟点赞数据初始化完成，共创建 " + likes.size() + " 个点赞");
    }

    private Like createLike(User user, Video video) {
        Like like = new Like();
        like.setUser(user);
        like.setVideo(video);
        like.setCreatedAt(LocalDateTime.now().minusDays((long) (Math.random() * 30)));
        return like;
    }

    private void initializeFollows(List<User> users) {
        Random random = new Random();
        // 如果只有一个用户，跳过关注初始化
        if (users.size() < 2) {
            System.out.println("用户数量不足，跳过关注数据初始化");
            return;
        }
        List<Follow> follows = Arrays.asList(
            createFollow(users.get(0), users.get(1)),
            createFollow(users.get(1), users.get(0))
        );
        followRepository.saveAll(follows);
        System.out.println("虚拟关注数据初始化完成，共创建 " + follows.size() + " 个关注");
    }

    private Follow createFollow(User follower, User followee) {
        Follow follow = new Follow();
        follow.setFollower(follower);
        follow.setFollowing(followee);
        follow.setCreatedAt(LocalDateTime.now().minusDays((long) (Math.random() * 30)));
        return follow;
    }

    private void initializeLiveStreams(List<User> users) {
        Random random = new Random();
        List<LiveStream> liveStreams = Arrays.asList(
            createLiveStream(users.get(0), "王者荣耀直播", "https://www.example.com/live/1"),
            createLiveStream(users.get(0), "和平精英直播", "https://www.example.com/live/2"),
            createLiveStream(users.get(0), "舞蹈教学直播", "https://www.example.com/live/3"),
            createLiveStream(users.get(0), "音乐创作直播", "https://www.example.com/live/4"),
            createLiveStream(users.get(0), "手工制作直播", "https://www.example.com/live/5"),
            createLiveStream(users.get(0), "健身教程直播", "https://www.example.com/live/6")
        );
        liveStreamRepository.saveAll(liveStreams);
        System.out.println("虚拟直播数据初始化完成，共创建 " + liveStreams.size() + " 个直播");
    }

    private LiveStream createLiveStream(User user, String title, String streamUrl) {
        LiveStream liveStream = new LiveStream();
        liveStream.setTitle(title);
        liveStream.setStreamUrl(streamUrl);
        liveStream.setStreamKey("stream_key_" + System.currentTimeMillis());
        liveStream.setUser(user);
        liveStream.setCreatedAt(LocalDateTime.now().minusDays((long) (Math.random() * 30)));
        return liveStream;
    }
} 